package com.common.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;

public class JsonToObject {
	
	/**
	 * 把json字符串转为特定的对象
	 * @author wuronglai
	 * @param jsonString
	 * @param object
	 * @return
	 * @throws Exception
	 */
	public static Object toObject(String jsonString,Object object) throws Exception{
		Class<? extends Object> objectClazz = object.getClass();
		
		JSONObject json = JSONObject.parseObject(jsonString);
		Set<String> keySet = json.keySet();
		Iterator<String> keys = keySet.iterator();
		while(keys.hasNext()){
			String key = keys.next();
			/*System.out.println(key);*/
			Field field = objectClazz.getDeclaredField(key);
			field.setAccessible(true);
			PropertyDescriptor pd = new PropertyDescriptor(field.getName(), objectClazz);
			Method method = pd.getWriteMethod();//获得写方法
			String property = json.get(key)+"";
			String type = field.getType().getName();
			
			switch (type) {
			case "java.lang.String":
				method.invoke(object, property);
				break;
			case "java.lang.Integer":
				method.invoke(object, Integer.parseInt(property));
				break;
			}
		}
		return object;
	}
	
	/**
	 * 把json字符串转为特定的对象
	 * @author wuronglai
	 * @param jsonString json字符串
	 * @param clazz 对象Class
	 * @return
	 * @throws Exception
	 */
	public static Object toObject(String jsonString,Class<?> clazz) throws Exception{
		Object instance = clazz.newInstance();
		JSONObject json = JSONObject.parseObject(jsonString);
		Set<String> keySet = json.keySet();
		Iterator<String> keys = keySet.iterator();
		while(keys.hasNext()){
			String key = keys.next();
			Field field = clazz.getDeclaredField(key);
			field.setAccessible(true);
			PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
			Method method = pd.getWriteMethod();//获得写方法
			String property = json.get(key)+"";
			String type = field.getType().getName();
			
			switch (type) {
			case "java.lang.String":
				method.invoke(instance, property);
				break;
			case "java.lang.Integer":
				method.invoke(instance, Integer.parseInt(property));
				break;
			}
		}
		return instance;
	}
}
